﻿using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Windows.Threading;

namespace XchangeStreamer.OutputSdk.Collections
{
    [Serializable]
    public class ReadOnlyObservableCollection<T> : System.Collections.ObjectModel.ReadOnlyObservableCollection<T>
    {
        public ReadOnlyObservableCollection(ObservableCollection<T> list)
            : base(list)
        { }

        protected override event System.Collections.Specialized.NotifyCollectionChangedEventHandler CollectionChanged;

        protected override void OnCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs args)
        {
            var eh = this.CollectionChanged;
            if (eh != null)
            {
                this.InternalOnCollectionChanged(args, eh);
            }
        }

        private void InternalOnCollectionChanged(NotifyCollectionChangedEventArgs e, NotifyCollectionChangedEventHandler eh)
        {
            DispatcherObject dispatcherObject;
            foreach (NotifyCollectionChangedEventHandler nh in eh.GetInvocationList())
            {
                dispatcherObject = nh.Target as DispatcherObject;
                if (dispatcherObject != null && dispatcherObject.Dispatcher != null && !dispatcherObject.Dispatcher.CheckAccess())
                {
                    dispatcherObject.Dispatcher.Invoke(DispatcherPriority.Normal, nh, this, e);
                }
                else
                {
                    nh(this, e);
                }
            }
        }
    }
}